package m.framework.controller;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import m.Config;
import m.framework.exception.SystemException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UrlParser{
	private static Logger log = LoggerFactory.getLogger(UrlParser.class);
	private static Map<String,ControllerMethod> map=new HashMap();
	 
	

	/**所有url的必须是${webRoot}/name/method.qunar的格式*/
	private static ControllerMethod createControllerMethod(String url) {
		url=url.replaceFirst(Config.webRoot(), "");
		int point=url.lastIndexOf('.');
		int line2=url.lastIndexOf('/');
		if(line2==-1){
		    log.warn("通过url:{}找不到对应的controller类:",url);
            return null;
		}
		int line1=url.substring(0, line2).lastIndexOf('/');
		String controllerName=url.substring(line1+1,line2);
		BaseController controller=ControllerHolder.get(controllerName);
		if(controller==null){
			log.warn("通过url:{}找不到对应的controller类:{}",url,controllerName);
			return null;
		}
		String methodName=url.substring(line2+1,point);
		for(Method m:controller.getClass().getMethods()){
			if(m.getName().equals(methodName)){
				return new ControllerMethod(controller, methodName);
			}
		}
		throw new SystemException("找不到"+url+"对应的controler方法");
	}

	public static ControllerMethod getMethod(String url){
		ControllerMethod method=map.get(url.toLowerCase());
		if(method==null){
			method=createControllerMethod(url);
			map.put(url.toLowerCase(),method);
		}
		return method;
	}
}
